//
//  PerfectCarInfoVC.m
//  Zhiche-Carriage
//
//  Created by LeeBruce on 16/6/16.
//  Copyright © 2016年 LeeBruce. All rights reserved.
//

#import "PerfectCarInfoVC.h"
#import "TopBackView.h"
#import "CarChoiceVC.h"
#import "CarSizeVC.h"
#import "QiniuSDK.h"
#import "Common.h"
#import <UIImageView+WebCache.h>
#import "PictureCollectionCell.h"
#import "WKProgressHUD.h"
#import "RootViewController.h"

#define spaceWidth 15 * kWidth


@interface PerfectCarInfoVC ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UITextFieldDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (nonatomic,strong) UIScrollView *scrollView;
@property (nonatomic,strong) UICollectionView *collectionView;

@property (nonatomic,strong) UITextField *nameField;
@property (nonatomic,strong) UITextField *qianNumberField;
@property (nonatomic,strong) UILabel *statusLabel;//审核状态
@property (nonatomic,strong) UILabel *commitLabel;//备注

@property (nonatomic,strong) UIButton *carStyleButton;
@property (nonatomic,strong) UIButton *carSizeButton;


@property (nonatomic,copy) NSString *token;
@property (nonatomic,copy) NSString *qiNiuKey;
@property (nonatomic,strong) UIImageView *imagev;
@property (nonatomic,strong) NSIndexPath *indexPath;

@property (nonatomic,strong) NSMutableDictionary *postDic;
@property (nonatomic,strong) NSMutableDictionary *dataDictionary;
@property (nonatomic,strong) NSMutableArray *postArray;


@property (nonatomic,strong) NSMutableArray *array1;
@property (nonatomic,strong) NSMutableArray *array2;
@property (nonatomic,strong) NSMutableArray *array3;
@property (nonatomic,strong) NSDictionary *carDictionary;



@end

@implementation PerfectCarInfoVC

- (void)viewDidLoad {
    [super viewDidLoad];
    TopBackView *topBackView= [[TopBackView alloc]initViewWithFrame:CGRectMake(0, 0, screenWidth, 64) andTitle:@"车辆信息完善"];
    self.dataDictionary = [NSMutableDictionary dictionary];

    self.postDic = [NSMutableDictionary dictionary];
    self.postArray = [NSMutableArray array];
    self.postDic = [NSMutableDictionary dictionary];

    
    topBackView.rightButton.hidden = YES;
    [topBackView.leftButton addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:topBackView];
    self.view.backgroundColor = [UIColor whiteColor];
    
    
    self.carDictionary = @{@"汽车列车":@"10",
                           @"救援车":@"20",
                           @"骨架":@"10",
                           @"半封闭":@"20",
                           @"全封闭":@"20",
                           @"2-6位":@"10",
                           @"7-12位":@"20"
                           };
    
    self.array1 = [NSMutableArray array];
    self.array2 = [NSMutableArray array];
    self.array3 = [NSMutableArray array];
    
    [self.postDic setValue:@"" forKey:@"typeCode"];//车辆种类编码
    [self.postDic setValue:@"" forKey:@"typeDesc"];//车辆种类描述
    [self.postDic setValue:@"" forKey:@"boxTypeCode"];//箱体结构编码
    [self.postDic setValue:@"" forKey:@"boxTypeDesc"];//箱体结构描述
    [self.postDic setValue:@"" forKey:@"storeNumberDesc"];//仓位数描述
    [self.postDic setValue:@"" forKey:@"storeNumberCode"];//仓位数编码
    [self.postDic setValue:@"" forKey:@"truckAnnex"];
    [self.postDic setValue:@"" forKey:@"userName"];//用户名
    [self.postDic setValue:@"" forKey:@"tractorNumber"];//牵引车车牌号
    [self.postDic setValue:@"" forKey:@"id"];//

    [self initDataSource];
    
//    [self initSubviews];
    
   }

-(void)initDataSource
{
    
    NSString *string = [NSString stringWithFormat:@"%@",find_truckinfo];
    
    [Common requestWithUrlString:string contentType:application_json finished:^(id responseObj) {
                
        self.dataDictionary = [NSMutableDictionary dictionaryWithDictionary:responseObj[@"data"]];
        

        if ([responseObj[@"success"] boolValue]) {
            
            [self initSubviews];
            [self findTruckStatus];
            
            [self giveValueStringWithDic:self.dataDictionary];
            
            [self.collectionView reloadData];
        }
        
        
    } failed:^(NSString *errorMsg) {
        NSLog(@"%@",errorMsg);
    }];
    

}

//查询车辆审核状态
-(void)findTruckStatus
{
    NSString *string = [NSString stringWithFormat:@"%@",truckinfo_status];
    
    [Common requestWithUrlString:string contentType:application_json finished:^(id responseObj) {
        
        
        
        if (![responseObj[@"data"] isKindOfClass:[NSNull class]]) {
            
            
            if ([responseObj[@"success"] boolValue]) {
                
                NSString *string ;
                
                if ([responseObj[@"data"] isEqualToString:@"10"]) {
                    string = @"审核中";
                } else  if ([responseObj[@"data"] isEqualToString:@"20"]) {
                    string = @"审核未通过";
                } else {
                    string = @"审核已通过";
                }
                
                self.statusLabel.text = [NSString stringWithFormat:@" %@",string];
                
            }
            
        }
        
        
    } failed:^(NSString *errorMsg) {
        NSLog(@"%@",errorMsg);
    }];
    
    
}


#pragma mark 赋值
-(void)giveValueStringWithDic:(NSMutableDictionary *)dic
{

    //真实姓名
    self.nameField.text = [NSString stringWithFormat:@"%@",dic[@"userName"]];
    //牵引车车牌号
    self.qianNumberField.text = [NSString stringWithFormat:@"%@",dic[@"tractorNumber"]];

    NSString *string ;
    if ([dic[@"comment"] isEqual:[NSNull null]]) {
        string = @"";
    } else {
        string = dic[@"comment"];
    }
    
    self.commitLabel.text = [NSString stringWithFormat:@"%@",string];
    
    
}


-(void)initSubviews
{
    self.scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 64, screenWidth, screenHeight - 64)];
    [self.view addSubview:self.scrollView];
    self.scrollView.backgroundColor = GrayColor;
    
    self.scrollView.contentSize = CGSizeMake(screenWidth, screenHeight * 1.5);
    
    [self initTextField];
    
    
    //审核信息
    
    self.statusLabel = [[UILabel alloc]init];
    self.commitLabel = [[UILabel alloc]init];
    
    UIView *V = [self backViewWithString:@"审核信息" andFrame:CGRectMake(0, 0, screenWidth, cellHeight * 3) andArray:@[@"审核状态:",@"备注:"] andLabel:@[self.statusLabel,self.commitLabel]];
    
    self.statusLabel.textColor = YellowColor;
    [self.scrollView addSubview:V];
    
    //基本信息
    UIView *firstV = [self backBackgroundViewWithString:@"基本信息" andFrame:CGRectMake(0, CGRectGetMaxY(V.frame) + 10, screenWidth, 3 * cellHeight)];
    
        [self.scrollView addSubview:firstV];
    //真实姓名
    UIView *nameV = [self backViewWithFrame:CGRectMake(0, cellHeight, screenWidth, cellHeight) andString:@"真实姓名:" andField:self.nameField];
    [firstV addSubview:nameV];
    
    //牵引车车牌号
    UIView *qianV = [self backViewWithFrame:CGRectMake(0, cellHeight * 2, screenWidth, cellHeight) andString:@"牵引车车牌号:" andField:self.qianNumberField];
    [firstV addSubview:qianV];
    
    
    //车辆类型
    
    UIView *thirdV = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(firstV.frame) + 10, screenWidth, cellHeight)];
    thirdV.tag = 400;
    thirdV.backgroundColor = WhiteColor;
    
    
    UIView *fourthV = [self backViewWithButtonArray1:@[@"骨架",@"半封闭",@"全封闭"] andOriginY:CGRectGetMaxY(thirdV.frame)];
    [self.scrollView addSubview:fourthV];
    for (UIButton *button in fourthV.subviews) {
        if ([button isKindOfClass:[UIButton class]]) {
            [self.array2 addObject:button];
            
        }
        
        if ([button.titleLabel.text isEqualToString:self.dataDictionary[@"boxTypeDesc"]]) {
            
            [self button3:button];
        }
        
    }
    
    
    
    UILabel *lineL1 = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, screenWidth, 0.5)];
    lineL1.backgroundColor = LineGrayColor;
    [fourthV addSubview:lineL1];
    
    
    
    UIView *fithV = [self backViewWithButtonArray1:@[@"2-6位",@"7-12位"] andOriginY:CGRectGetMaxY(fourthV.frame)];
    [self.scrollView addSubview:fithV];
    for (UIButton *button in fithV.subviews) {
        if ([button isKindOfClass:[UIButton class]]) {
            [self.array3 addObject:button];
        }
        
        if ([button.titleLabel.text isEqualToString:self.dataDictionary[@"storeNumberDesc"]]) {
            
            [self button3:button];
        }
    }
    
    
    
    UILabel *lineL2 = [[UILabel alloc]initWithFrame:CGRectMake(18, 0, screenWidth, 0.5)];
    lineL2.backgroundColor = LineGrayColor;
    [fithV addSubview:lineL2];
    
    
    //汽车列表
    UIButton *qicheButton = [UIButton buttonWithType:UIButtonTypeCustom];
    qicheButton.frame = CGRectMake(18 , 10 * kHeight, 60 * kWidth, cellHeight - 20 * kHeight);
    [qicheButton setTitle:@"汽车列车" forState:UIControlStateNormal];
    [qicheButton setTitleColor:littleBlackColor forState:UIControlStateNormal];
    qicheButton.backgroundColor = GrayColor;
    
    [qicheButton addTarget:self action:@selector(button1:) forControlEvents:UIControlEventTouchUpInside];
    qicheButton.layer.cornerRadius = 5;
    qicheButton.layer.borderColor = fontGrayColor.CGColor;
    qicheButton.layer.borderWidth = 0.5;
    [thirdV addSubview:qicheButton];
    qicheButton.titleLabel.font = Font(12);
    qicheButton.tag = 401;
    
    
    //救援车
    
    //汽车列表
    UIButton *jiuyuanButton = [UIButton buttonWithType:UIButtonTypeCustom];
    jiuyuanButton.frame = CGRectMake(CGRectGetMaxX(qicheButton.frame) + spaceWidth , 10 * kHeight, 60 * kWidth, cellHeight - 20 * kHeight);
    [jiuyuanButton setTitle:@"救援车" forState:UIControlStateNormal];
    [jiuyuanButton setTitleColor:littleBlackColor forState:UIControlStateNormal];
    [jiuyuanButton addTarget:self action:@selector(button2:) forControlEvents:UIControlEventTouchUpInside];
    jiuyuanButton.layer.cornerRadius = 5;
    jiuyuanButton.layer.borderColor = fontGrayColor.CGColor;
    jiuyuanButton.layer.borderWidth = 0.5;
    [thirdV addSubview:jiuyuanButton];
    jiuyuanButton.titleLabel.font = Font(12);
    jiuyuanButton.backgroundColor = GrayColor;
    jiuyuanButton.tag = 402;
    
    [self.scrollView addSubview:thirdV];

    
    for (UIButton *button in thirdV.subviews) {
        if ([button isKindOfClass:[UIButton class]]) {
            [self.array1 addObject:button];
            
        }
        
        if ([self.dataDictionary[@"typeDesc"] isEqualToString:@"汽车列车"]) {
            
            [self button1:qicheButton];
        } else {
            [self button2:jiuyuanButton];
        }
        
    }
    

    
    [self initCollectionView];


}

-(void)initTextField
{
    self.nameField = [[UITextField alloc]init];
    self.qianNumberField = [[UITextField alloc]init];
    
    
    self.nameField.borderStyle = UITextBorderStyleRoundedRect;
    self.qianNumberField.borderStyle = UITextBorderStyleRoundedRect;

}


-(void)initCollectionView
{
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    layout.itemSize = CGSizeMake(80 * kWidth, 80 * kHeight);
    layout.minimumInteritemSpacing = 0;
    
    
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, cellHeight * 9 + 20, screenWidth, 3 * 120 * kHeight) collectionViewLayout:layout];
    
    
    [self.scrollView addSubview:self.collectionView];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.backgroundColor = WhiteColor;
    
    [self.collectionView registerClass:[PictureCollectionCell class] forCellWithReuseIdentifier:@"carInfoCell"];
    
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerView"];
    
    [self initBottomButton];

}


#pragma mark  UICollectionViewDelegate,UICollectionViewDataSource

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 3;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    
    if (section == 0) {
        return  [self.dataDictionary[@"truckPicMap"][@"item"] count];
    } else
        
        if (section == 1) {
            
            
            return  [self.dataDictionary[@"licensePicMap"][@"item"] count];
            
        } else
            
        {
            
            return  [self.dataDictionary[@"insurePicMap"][@"item"] count];
            
        }
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    static NSString *cellIden = @"carInfoCell";
    PictureCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIden forIndexPath:indexPath];
    
    cell.ImageView.backgroundColor = YellowColor;
    if (indexPath.section == 0) {
        
        cell.label.text = [NSString stringWithFormat:@"%@",self.dataDictionary[@"truckPicMap"][@"item"][indexPath.row][@"picDesc"]];
        NSURL * url = [NSURL URLWithString:[NSString stringWithFormat:@"%@",self.dataDictionary[@"truckPicMap"][@"item"][indexPath.row][@"picKey"]]];
        
        [cell.ImageView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"1"]];
        [cell.ImageView sd_setImageWithURL:url];
        
        
    }
    
    if (indexPath.section == 1) {
        
        
        cell.label.text = [NSString stringWithFormat:@"%@",self.dataDictionary[@"licensePicMap"][@"item"][indexPath.row][@"picDesc"]];
        
        NSURL * url = [NSURL URLWithString:[NSString stringWithFormat:@"%@",self.dataDictionary[@"licensePicMap"][@"item"][indexPath.row][@"picKey"]]];
        
        [cell.ImageView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"1"]];
        [cell.ImageView sd_setImageWithURL:url];

    }
    
    if (indexPath.section == 2) {
        cell.label.text = [NSString stringWithFormat:@"%@",self.dataDictionary[@"insurePicMap"][@"item"][indexPath.row][@"picDesc"]];
        
        NSURL * url = [NSURL URLWithString:[NSString stringWithFormat:@"%@",self.dataDictionary[@"insurePicMap"][@"item"][indexPath.row][@"picKey"]]];
        
        [cell.ImageView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"1"]];
        [cell.ImageView sd_setImageWithURL:url];
    }
    
    return cell;
    
}
//头标题尺寸
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    return CGSizeMake(screenWidth, 30 * kHeight);
}
//items的偏移量
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(5, 14, 5, 14);
}

//头标题
-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerView" forIndexPath:indexPath];
    
    for (UILabel *view in headerView.subviews) {
        [view removeFromSuperview];
    }
    UILabel *lable = [[UILabel alloc]initWithFrame:CGRectMake(14, 0, 150, headerView.frame.size.height)];
    lable.font = Font(15);
    NSArray *array = @[self.dataDictionary[@"truckPicMap"][@"name"],self.dataDictionary[@"licensePicMap"][@"name"],self.dataDictionary[@"insurePicMap"][@"name"]];
    
    lable.text = array[indexPath.section];
    
    [headerView addSubview:lable];
    headerView.backgroundColor = GrayColor;
    
    
    return headerView;
}



-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    self.indexPath = indexPath;
    [self photoButton];

}


-(void)initBottomButton{
    
    UIButton *bottomButton = [UIButton buttonWithType:UIButtonTypeCustom];
    bottomButton.frame = CGRectMake(20, CGRectGetMaxY(self.collectionView.frame) + 20, screenWidth - 40, 35);
    [bottomButton setTitle:@"确认" forState:UIControlStateNormal];
    [bottomButton setTitleColor:WhiteColor forState:UIControlStateNormal];
    bottomButton.titleLabel.font = Font(16);
    bottomButton.backgroundColor = YellowColor;
    bottomButton.layer.cornerRadius = 5;
    [bottomButton addTarget:self action:@selector(confirmButton) forControlEvents:UIControlEventTouchUpInside];
    [self.scrollView addSubview:bottomButton];
    bottomButton.tag = 404;
    
    
}

-(void)confirmButton
{
    
    
    NSData * jsonData = [NSJSONSerialization dataWithJSONObject:self.postArray options:NSJSONWritingPrettyPrinted error:nil];
    NSString * jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    [self.postDic setObject:self.nameField.text forKey:@"userName"];
    [self.postDic setObject:self.qianNumberField.text forKey:@"tractorNumber"];
    [self.postDic setObject:jsonString forKey:@"truckAnnex"];

    
    NSString *idS ;
    
    if ([self.dataDictionary[@"id"] isEqual:[NSNull null]]) {
        idS = @"";
    } else {
        idS = self.dataDictionary[@"id"];
    }
    
    [self.postDic setObject:idS forKey:@"id"];
    
    
    Common *c = [[Common alloc]init];
    [c afPostRequestWithUrlString:truckinfo_add parms:self.postDic finishedBlock:^(id responseObj) {
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObj options:NSJSONReadingMutableLeaves error:nil];
        
        [WKProgressHUD popMessage:dic[@"message"] inView:self.view duration:1.5 animated:YES];

        
    } failedBlock:^(NSString *errorMsg) {
        NSLog(@"%@",errorMsg);
    }];
    
}


-(UIView *)backBackgroundViewWithString:(NSString *)string andFrame:(CGRect)frame
{
    UIView *view = [[UIView alloc]initWithFrame:frame];
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(14, 0, 100, cellHeight)];
    label.font =Font(15);
    label.text = string;
    [view addSubview:label];
    
    label.textColor = littleBlackColor;
    view.backgroundColor = WhiteColor;
    
    return view;
}



-(UIView *)backViewWithFrame:(CGRect)frame andString:(NSString *)string andField:(UITextField *)field
{
    UILabel *labe = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, screenWidth, 0.5)];
    labe.backgroundColor = GrayColor;
    
    
    
    UIView *view = [[UIView alloc]initWithFrame:frame];
    view.backgroundColor = WhiteColor;
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(14, 0, 80 * kWidth, cellHeight)];
    label.font = Font(12);
    label.text = string;
    label.textColor = fontGrayColor;
    [view addSubview:label];
    [view addSubview:labe];
    
    
    field.frame = CGRectMake(CGRectGetMaxX(label.frame), 5, 185 * kWidth, cellHeight - 10);
    field.font = Font(12);
    [view addSubview:field];
    field.delegate = self;
    field.textColor = littleBlackColor;
    
    
    
    return view;
}

-(UIButton *)backButton
{
    UIButton *bottomButton = [UIButton buttonWithType:UIButtonTypeCustom];
    bottomButton.frame = CGRectMake(20,0, screenWidth - 40, cellHeight);
    [bottomButton setTitleColor:BlackColor forState:UIControlStateNormal];
    bottomButton.titleLabel.font = Font(15);
    bottomButton.backgroundColor = WhiteColor;
    bottomButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    
    return bottomButton;

}

-(UIView *)backViewWithButtonArray1:(NSArray *)array andOriginY:(CGFloat)y
{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, y, screenWidth, cellHeight)];
    view.backgroundColor = WhiteColor;
    
    for (int i = 0; i < array.count; i++) {
        
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        
        button.frame = CGRectMake(18 + (60 * kWidth + spaceWidth) * i, 10 * kHeight, 60 * kWidth, cellHeight - 20 * kHeight);
        [button setTitle:array[i] forState:UIControlStateNormal];
        [button setTitleColor:fontGrayColor forState:UIControlStateNormal];
        [button addTarget:self action:@selector(button3:) forControlEvents:UIControlEventTouchUpInside];
        button.layer.cornerRadius = 5;
        button.layer.borderColor = fontGrayColor.CGColor;
        button.layer.borderWidth = 0.5;
        [view addSubview:button];
        button.titleLabel.font = Font(12);
        
        [self.array1 addObject:button];
    }
    
    [self.scrollView addSubview:view];
    
    return view;
    
    
}


-(void)backAction
{
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark 获取图片
-(void)photoButton
{
    __weak typeof(self) weakSelf = self;
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [weakSelf getPictureFromCamera];
        
    }];
    UIAlertAction *action3 = [UIAlertAction actionWithTitle:@"从相册选取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf getPictureFromLibrary];
        
    }];
    
    [alert addAction:action1];
    [alert addAction:action2];
    [alert addAction:action3];
    
    
    [self presentViewController:alert animated:YES completion:nil];
    
}

#pragma mark 拍照
-(void)getPictureFromCamera
{
    UIImagePickerController *picker = [[UIImagePickerController alloc]init];
    picker.delegate = self;
    picker.allowsEditing = YES;
    picker.sourceType = UIImagePickerControllerSourceTypeCamera;
    
    [self presentViewController:picker animated:YES completion:nil];
}

#pragma mark 从相册选取
-(void)getPictureFromLibrary
{
    UIImagePickerController *picker = [[UIImagePickerController alloc]init];
    picker.delegate = self;
    picker.allowsEditing = YES;
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    
    [self presentViewController:picker animated:YES completion:nil];
    
}

#pragma mark 从七牛获取Token
-(void)getTokenFromQN
{
    
    [Common requestWithUrlString:qiniu_token contentType:application_json finished:^(id responseObj) {
        if ([responseObj[@"success"] boolValue]) {
            
            PictureCollectionCell *pictureCell = (PictureCollectionCell *)[self.collectionView cellForItemAtIndexPath:self.indexPath];
            
            
            self.token = responseObj[@"data"];
            [self uploadImageToQNWithData:[self getImageWith:pictureCell.ImageView.image]];
        }
    } failed:^(NSString *errorMsg) {
        NSLog(@"%@",errorMsg);
    }];
    
    
}

-(NSData *)getImageWith:(UIImage *)image
{
    NSData *data = nil;
    if (UIImagePNGRepresentation(image)) {
        
        data = UIImageJPEGRepresentation(image, 1);
        
        
    } else {
        data = UIImagePNGRepresentation(image);
        
        
    }
    
    return data;
}


-(void)uploadImageToQNWithData:(NSData *)data
{
    
    QNUploadManager *upManager = [[QNUploadManager alloc]init];
    
    QNUploadOption *uploadOption = [[QNUploadOption alloc]initWithMime:nil progressHandler:^(NSString *key, float percent) {
        
    } params:nil checkCrc:NO cancellationSignal:nil];
    
    [upManager putData:data key:nil token:self.token complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
        
        NSLog(@"%@",resp);
        NSDictionary *dic = [NSDictionary dictionary];
        self.qiNiuKey = resp[@"key"];
        NSString *string1 ;
        NSString *string2 ;
        NSString *string3 ;
        
        
        if (self.indexPath.section == 0) {
            
            if ([self.dataDictionary[@"truckPicMap"][@"item"][self.indexPath.row][@"id"] isEqual:[NSNull null]]  ) {
                string1 = @"";
            } else {
                string1 = [NSString stringWithFormat:@"%@",self.dataDictionary[@"truckPicMap"][@"item"][self.indexPath.row][@"id"]];
            }
            
            
            dic = @{@"id": string1 ,
                    @"picType":[NSString stringWithFormat:@"%@",self.dataDictionary[@"truckPicMap"][@"item"][self.indexPath.row][@"picType"]],
                    @"picItem":[NSString stringWithFormat:@"%@",self.dataDictionary[@"truckPicMap"][@"item"][self.indexPath.row][@"picItem"]],
                    @"picKey":resp[@"key"],
                    @"picDesc":[NSString stringWithFormat:@"%@",self.dataDictionary[@"truckPicMap"][@"item"][self.indexPath.row][@"picDesc"]]};
            
            
        }
        
        if (self.indexPath.section == 2) {
            
            if ([self.dataDictionary[@"insurePicMap"][@"item"][self.indexPath.row][@"id"] isEqual:[NSNull null]]  ) {
                string2 = @"";
            } else {
                string2 = [NSString stringWithFormat:@"%@",self.dataDictionary[@"insurePicMap"][@"item"][self.indexPath.row][@"id"]];
            }
            
            
            
            dic = @{@"id": string2 ,
                    @"picType":[NSString stringWithFormat:@"%@",self.dataDictionary[@"insurePicMap"][@"item"][self.indexPath.row][@"picType"]],
                    @"picItem":[NSString stringWithFormat:@"%@",self.dataDictionary[@"insurePicMap"][@"item"][self.indexPath.row][@"picItem"]],
                    @"picKey":resp[@"key"],
                    @"picDesc":[NSString stringWithFormat:@"%@",self.dataDictionary[@"insurePicMap"][@"item"][self.indexPath.row][@"picDesc"]]};
        }
        
        if (self.indexPath.section == 1) {
            
            if ([self.dataDictionary[@"licensePicMap"][@"item"][self.indexPath.row][@"id"] isEqual:[NSNull null]]  ) {
                string3 = @"";
            } else {
                string3 = [NSString stringWithFormat:@"%@",self.dataDictionary[@"licensePicMap"][@"item"][self.indexPath.row][@"id"]];
            }
            
            
            
            dic = @{@"id": string3,
                    @"picType":[NSString stringWithFormat:@"%@",self.dataDictionary[@"licensePicMap"][@"item"][self.indexPath.row][@"picType"]],
                    @"picItem":[NSString stringWithFormat:@"%@",self.dataDictionary[@"licensePicMap"][@"item"][self.indexPath.row][@"picItem"]],
                    @"picKey":resp[@"key"],
                    @"picDesc":[NSString stringWithFormat:@"%@",self.dataDictionary[@"licensePicMap"][@"item"][self.indexPath.row][@"picDesc"]]};
        }
        
        
        
        if (self.postArray.count > 0) {
            for (int i = 0; i < self.postArray.count; i++) {
                
                if ([self.postArray[i][@"picItem"] isEqualToString:dic[@"picItem"]]) {

                    [self.postArray removeObjectAtIndex:i];

                }
            }
                [self.postArray addObject:dic];

            
            
        } else {
            
            [self.postArray addObject:dic];
            
        }
        
        
    } option:uploadOption];
}


#pragma mark UIImagePickerControllerDelegate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    
    
    [picker dismissViewControllerAnimated:YES completion:^{
        
        UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
        
        PictureCollectionCell *pictureCell = (PictureCollectionCell *)[self.collectionView cellForItemAtIndexPath:self.indexPath];
        
        pictureCell.ImageView.image = image;
        
//        self.imagev.image = image;
        
        //上传服务器
        [self getTokenFromQN];
        
    }];
}


-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    [self.view endEditing:NO];
}

//点击return 按钮 去掉
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}


//汽车
-(void)button1:(UIButton *)sender
{
    
    UIButton *button = (UIButton *)[self.view viewWithTag:402];
    button.backgroundColor = GrayColor;
    [button setTitleColor:littleBlackColor forState:UIControlStateNormal];
    
    
    sender.backgroundColor = YellowColor;
    [sender setTitleColor:WhiteColor forState:UIControlStateNormal];
    sender.layer.borderWidth = 0;
    
    
    UIView *view = (UIView *)[self.view viewWithTag:400];
    
    [UIView animateWithDuration:0.2 animations:^{
        
        self.collectionView.frame = CGRectMake(0, CGRectGetMaxY(view.frame) + cellHeight * 2, screenWidth, 3 * 120 * kHeight);
        
        UIButton *button = [self.view viewWithTag:404];
        button.frame = CGRectMake(button.frame.origin.x, CGRectGetMaxY(self.collectionView.frame) + 20, button.frame.size.width, button.frame.size.height);
        
    }];
    
    [self.postDic setValue:self.carDictionary[sender.titleLabel.text] forKey:@"typeCode"];//车辆种类编码
    [self.postDic setValue:sender.titleLabel.text forKey:@"typeDesc"];//车辆种类描述
    
}



//救援
-(void)button2:(UIButton *)sender
{
    UIButton *button = (UIButton *)[self.view viewWithTag:401];
    button.backgroundColor = GrayColor;
    [button setTitleColor:littleBlackColor forState:UIControlStateNormal];
    
    sender.backgroundColor = YellowColor;
    [sender setTitleColor:WhiteColor forState:UIControlStateNormal];
    sender.layer.borderWidth = 0;
    
    UIView *view = (UIView *)[self.view viewWithTag:400];
    [UIView animateWithDuration:0.2 animations:^{
        
        self.collectionView.frame = CGRectMake(0, CGRectGetMaxY(view.frame) , screenWidth, 3 * 120 * kHeight);
        
        UIButton *button = [self.view viewWithTag:404];
        button.frame = CGRectMake(button.frame.origin.x, CGRectGetMaxY(self.collectionView.frame) + 20, button.frame.size.width, button.frame.size.height);
        
        
    }];
    
    [self.postDic setValue:self.carDictionary[sender.titleLabel.text] forKey:@"typeCode"];//车辆种类编码
    [self.postDic setValue:sender.titleLabel.text forKey:@"typeDesc"];//车辆种类描述
    [self.postDic setValue:@"" forKey:@"boxTypeCode"];//箱体结构编码
    [self.postDic setValue:@"" forKey:@"boxTypeDesc"];//箱体结构描述
    [self.postDic setValue:@"" forKey:@"storeNumberDesc"];//仓位数描述
    [self.postDic setValue:@"" forKey:@"storeNumberCode"];//仓位数编码
    
    
}

-(void)button3:(UIButton *)sender
{
    
    if ([self.array2 containsObject:sender]) {
        
        for (int i = 0; i < self.array2.count; i ++) {
            UIButton *button = self.array2[i];
            if (button == sender) {
                
                sender.layer.borderWidth = 0.5;
                sender.layer.borderColor = YellowColor.CGColor;
                [sender setTitleColor:YellowColor forState:UIControlStateNormal];
                
            } else {
                
                button.layer.borderWidth = 0.5;
                button.layer.borderColor = fontGrayColor.CGColor;
                [button setTitleColor:fontGrayColor forState:UIControlStateNormal];
                
                
            }
            
            
        }
        
        [self.postDic setValue:self.carDictionary[sender.titleLabel.text] forKey:@"boxTypeCode"];//箱体结构编码
        [self.postDic setValue:sender.titleLabel.text forKey:@"boxTypeDesc"];//箱体结构描述
        
        
    } else {
        
        for (int i = 0; i < self.array3.count; i ++) {
            UIButton *button = self.array3[i];
            if (button == sender) {
                
                sender.layer.borderWidth = 0.5;
                sender.layer.borderColor = YellowColor.CGColor;
                [sender setTitleColor:YellowColor forState:UIControlStateNormal];
                
                
            } else {
                
                button.layer.borderWidth = 0.5;
                button.layer.borderColor = fontGrayColor.CGColor;
                [button setTitleColor:fontGrayColor forState:UIControlStateNormal];
                
                
                
            }
            
            
        }
        
        
    }
    
    [self.postDic setValue:self.carDictionary[sender.titleLabel.text] forKey:@"storeNumberCode"];//箱体结构编码
    [self.postDic setValue:sender.titleLabel.text forKey:@"storeNumberDesc"];//箱体结构描述
    
    
    
}

-(UIView *)backViewWithString:(NSString *)string andFrame:(CGRect )frame andArray:(NSArray *)titleArray andLabel:(NSArray *)labelArray
{
    UIView *backView = [[UIView alloc]initWithFrame:frame];
    backView.backgroundColor = WhiteColor;
    //上面标题
    UILabel *titleL = [[UILabel alloc]initWithFrame:CGRectMake(18, 0, 100, cellHeight)];
    
    titleL.text = string;
    titleL.textColor = littleBlackColor;
    titleL.font = Font(15);
    [backView addSubview:titleL];
    
    UILabel *lineL1 = [[UILabel alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(titleL.frame ) - 0.5, screenWidth, 0.5)];
    lineL1.backgroundColor = LineGrayColor;
    [backView addSubview:lineL1];
    
    
    if (labelArray.count > 0) {
        
        
        for (int i = 0; i < titleArray.count; i++) {
            
            UIView *view = [self backWhiteViewWithString:titleArray[i] andLabel:labelArray[i] andFrame:CGRectMake(0, cellHeight + i * cellHeight, screenWidth , cellHeight)];
            [backView addSubview:view];
            
        }
    }
    
    return backView;
}

-(UIView *)backWhiteViewWithString:(NSString *)string andLabel:(UILabel *)label andFrame:(CGRect)frame
{
    
    UIView *view = [[UIView alloc]initWithFrame:frame];
    view.backgroundColor = WhiteColor;
    
    UILabel *titleLabel = [[UILabel alloc]init];
    if (string.length > 0) {
        
        titleLabel.frame = CGRectMake(18, 0, 100 * kWidth, frame.size.height);
        titleLabel.text = string;
        
        
    } else {
        titleLabel.frame = CGRectMake(18, 0, 0, frame.size.height);
    }
    
    titleLabel.font = Font(12);
    titleLabel.text = string;
    titleLabel.textColor = fontGrayColor;
    titleLabel.textAlignment = NSTextAlignmentLeft;
    [view addSubview:titleLabel];
    
    label.frame = CGRectMake(CGRectGetMaxX(titleLabel.frame), 0, screenWidth - 120, frame.size.height);
    label.font = Font(12);
    [view addSubview:label];
    
    UILabel *lineL = [[UILabel alloc]initWithFrame:CGRectMake(0, frame.size.height - 0.5, screenWidth, 0.5)];
    lineL.backgroundColor = LineGrayColor;
    [view addSubview:lineL];
    
    
    return view;
}

-(void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBarHidden = YES;
    
    RootViewController *rootVC = [RootViewController defaultsTabBar];
    [rootVC setTabBarHidden:YES];
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
